package day07;

import java.util.Arrays;
import java.util.Random;

/**
 * 需求:生成指定位数验证码(大写字母、小写字母、数字)
 */
//第一种方法生成的验证码中,不一定有数字
//第二种方法生成的验证码中一定有一位数字,但位置不可变
//第三种方法生成的验证码中必有一位数字,且出现位置随机
public class VerificationCode {
    public static void main(String[] args) {
        String code = generateVeriCode(7);
        System.out.println("验证码:" + code);
    }

    public static String generateVeriCode(int len) {
        Random r = new Random();
        char[] arr1 = new char[52];
        char[] arr2 = new char[10];
        for (int i = 0; i < 26; i++) {
            arr1[i] = (char) ('a' + i);
        }
        for (int i = 26; i < 52; i++) {
            arr1[i] = (char) ('A' + i - 26);
        }
        for (int i = 0; i < 10; i++) {
            arr2[i] = (char) ('0' + i);
        }
        String code = "";
        int index;

        for (int i = 0; i < (len - 1); i++) {
            index = r.nextInt(arr1.length);
            code += arr1[index];
        }
        code += arr2[r.nextInt(arr2.length)];
        char[] chars = code.toCharArray();
        int index2 = r.nextInt(len);
        char temp = chars[len - 1];
        chars[len - 1] = chars[index2];
        chars[index2] = temp;
        code = "";
        for (int i = 0; i < chars.length; i++) {
            code += chars[i];
        }
        return code;
    }

 /*方法二
   public static String generateVeriCode(int len) {
        Random r = new Random();
        char[] arr1 = new char[52];
        char[] arr2 = new char[10];
        for (int i = 0; i < 26; i++) {
            arr1[i] = (char) ('a' + i);
        }
        for (int i = 26; i < 52; i++) {
            arr1[i] = (char) ('A' + i - 26);
        }
        for (int i = 0; i < 10; i++) {
            arr2[i] = (char) ('0' + i);
        }
        String code = "";
        int index;

        for (int i = 0; i < (len - 1); i++) {
            index = r.nextInt(arr1.length);
            code += arr1[index];
        }
        code += arr2[r.nextInt(arr2.length)];

        return code;
    }*/


  /*方法一
   public static String generateVeriCode(int len) {
        String code = "";
        char[] chars = new char[62];
        for (int i = 0; i < 26; i++) {
            chars[i] = (char) ('a' + i);
        }
        for (int i = 26; i < 52; i++) {
            chars[i] = (char) ('A' + i - 26);
        }
        for (int i = 52; i < 62; i++) {
            chars[i] = (char) ('0' + i - 52);
        }
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            int index = r.nextInt(chars.length);
            code += chars[index];
        }
        return code;
    }*/
}
